
package com.dyzx.hbb.security.service;

import com.alibaba.fastjson2.JSONObject;
import com.dyzx.hbb.modules.sys.entity.SysUser;
import com.dyzx.hbb.modules.sys.service.SysUserService;
import com.dyzx.hbb.security.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户详情服务实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户

        SysUser user = userService.getByAccount(username);

        System.out.println("user:"+user);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        
        return createLoginUser(user);
    }

    /**
     * 根据用户ID加载用户信息
     */
   // @Cacheable(value = "token::userCache:userId", key = "#userId")
    public UserDetails loadUserById(Long userId) throws UsernameNotFoundException {
        // 根据ID查询用户
        String key="token::userCache:userId:"+userId;
        SysUser user = null;
        if(!stringRedisTemplate.hasKey(key)){
            user = userService.getById(userId);
            if (user == null) {
                throw new UsernameNotFoundException("用户不存在");
            }
            stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString( user));
        }else{
            user = JSONObject.parseObject(stringRedisTemplate.opsForValue().get(key), SysUser.class);
        }


        return createLoginUser(user);
    }

    /**
     * 创建LoginUser对象
     */
    private LoginUser createLoginUser(SysUser user) {
        // 获取用户权限列表

        List<String> permissions =userService.getMenuPermissions(user.getId());
        if (permissions == null) {
            permissions = List.of();
        }


        
        // 获取数据权限范围
        String dataScope = determineDataScope(user);
        
        // 创建LoginUser对象
        return new LoginUser(user, permissions, dataScope);
    }

    /**
     * 确定用户的数据权限范围
     */
    private String determineDataScope(SysUser user) {

        // TODO: 根据用户角色确定具体的数据权限范围
        // 可能的值：ALL-所有数据、DEPT-本部门数据、DEPT_CHILD-本部门及以下数据、SELF-仅本人数据
        return "ALL"; // 默认只能查看本部门数据
    }
}